package com.lxd.sunso.product.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lxd.sunso.common.utils.PageUtils;
import com.lxd.sunso.common.utils.Query;
import com.lxd.sunso.product.entity.CustomerEntity;
import com.lxd.sunso.product.entity.DatatemplateEntity;
import com.lxd.sunso.product.entity.MachineEntity;
import com.lxd.sunso.product.service.CustomerService;
import com.lxd.sunso.product.service.DatatemplateService;
import com.lxd.sunso.product.service.MachineService;
import com.lxd.sunso.product.vo.AlarmhisDataVo;
import com.lxd.sunso.product.vo.HistoryDataVo;
import com.lxd.sunso.product.vo.PageModel;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxd.sunso.product.dao.AlarmhisdataDao;
import com.lxd.sunso.product.entity.AlarmhisdataEntity;
import com.lxd.sunso.product.service.AlarmhisdataService;

import javax.servlet.http.HttpServletResponse;


@Service("alarmhisdataService")
public class AlarmhisdataServiceImpl extends ServiceImpl<AlarmhisdataDao, AlarmhisdataEntity> implements AlarmhisdataService {

    @Autowired
    private CustomerService customerService;

    @Autowired
    private MachineService machineService;

    @Autowired
    private DatatemplateService datatemplateService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AlarmhisdataEntity> page = this.page(
                new Query<AlarmhisdataEntity>().getPage(params),
                new QueryWrapper<AlarmhisdataEntity>()
        );

        List<AlarmhisdataEntity> list = addMessage(page.getRecords());

        page.setRecords(list);

        return new PageUtils(page);
    }

    @Override
    public PageUtils search(Map<String, Object> params) {
        String machineName = (String) params.get("machineName");
        String datatemplateId = (String) params.get("datatemplateId");
        String startTime = (String) params.get("startTime");
        String endTime = (String) params.get("endTime");

        QueryWrapper<AlarmhisdataEntity> queryWrapper = new QueryWrapper<>();

        MachineEntity machineEntity = null;

        if (!StringUtils.isEmpty(machineName)) {
            machineEntity = machineService.getOne(new QueryWrapper<MachineEntity>().eq("MachineName", machineName));
            if (machineEntity != null) {
                queryWrapper.eq("MachineID", machineEntity.getId());
            }
        }

        if (!StringUtils.isEmpty(datatemplateId)) {
            queryWrapper.eq("DatatemplateId", datatemplateId);
        }

        if (!StringUtils.isEmpty(startTime)) {

            queryWrapper.ge("CreateTime", startTime);
        }

        if (!StringUtils.isEmpty(endTime)) {
            endTime += " 23:59:59";
            queryWrapper.le("CreateTime", endTime);
        }

        queryWrapper.orderByDesc("CreateTime");

        List<AlarmhisdataEntity> entities = this.list(queryWrapper);

        MachineEntity finalMachineEntity = machineEntity;

        List<AlarmhisDataVo> list = entities.stream().map(entity -> {
            AlarmhisDataVo alarmhisDataVo = new AlarmhisDataVo();
            alarmhisDataVo.setMachineName(machineName);
            DatatemplateEntity datatemplateEntity = datatemplateService.getById(entity.getDatatemplateid());
            alarmhisDataVo.setControlName(datatemplateEntity.getControlname());
            alarmhisDataVo.setDataAddress(datatemplateEntity.getRegisteraddress());
            CustomerEntity customerEntity = customerService.getById(finalMachineEntity.getCustomerid());
            alarmhisDataVo.setCustomerName(customerEntity.getCustomername());
            alarmhisDataVo.setCreatetime(entity.getCreatetime());
            alarmhisDataVo.setDatavalue(entity.getDatavalue());
            alarmhisDataVo.setAlarmcontent(entity.getAlarmcontent());
            return alarmhisDataVo;
        }).collect(Collectors.toList());

        //默认当前页为1
        Integer currentPage =1;

        //默认每页数量为10
        Integer limit = 100000000;

        String value = (String) params.get("limit"); //每页的数量
        if (!StringUtils.isEmpty(value)) {
            limit = Integer.valueOf(value);
        }

        String data = (String) params.get("page");//当前页
        if (!StringUtils.isEmpty(data)) {
            currentPage = Integer.valueOf(data);
        }

        //利用工具类进行数据拆分
        PageModel pm = new PageModel(list, limit);
        List list1 = pm.getObjects(currentPage);

        Page<HistoryDataVo> page = new Page<>();
        page.setTotal(list.size());
        page.setCurrent(currentPage);
        page.setSize(Integer.valueOf(value));
        page.setRecords(list1);

        return new PageUtils(page);
    }

    @Override
    public void exportExcel(HttpServletResponse response, Map<String, Object> params) throws IOException {
        // 第一步，创建一个webbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet("test");
        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        HSSFRow row = sheet.createRow(0);
        // 第四步，创建单元格，并设置值表头 设置表头居中
        HSSFCellStyle style = wb.createCellStyle();
        // 创建一个居中格式

        /*此处根据情况自己自定义样式*/
        style.setBottomBorderColor(HSSFColor.BLACK.index);

        HSSFCell cell = row.createCell(0);
        cell.setCellValue("设备ID");
        cell.setCellStyle(style);
        cell = row.createCell(1);
        cell.setCellValue("客户名称");
        cell.setCellStyle(style);
        cell = row.createCell(2);
        cell.setCellValue("数据名称");
        cell.setCellStyle(style);
        cell = row.createCell(3);
        cell.setCellValue("数据地址");
        cell.setCellStyle(style);
        cell = row.createCell(4);
        cell.setCellValue("报警内容");
        cell.setCellStyle(style);
        cell = row.createCell(5);
        cell.setCellValue("实时数据值");
        cell.setCellStyle(style);
        cell = row.createCell(6);
        cell.setCellValue("时间");
        cell.setCellStyle(style);

        // 第五步，写入实体数据 实际应用中这些数据从数据库得到，
        PageUtils pageUtils = this.search(params);
        List<AlarmhisDataVo> list = (List<AlarmhisDataVo>) pageUtils.getList();
        if (list!=null){
            for (int i = 0; i < list.size(); i++) {
                row = sheet.createRow(i + 1);
                AlarmhisDataVo alarmhisDataVo = list.get(i);
                // 创建单元格，并设置值
                row.createCell(0).setCellValue(alarmhisDataVo.getMachineName());
                row.createCell(1).setCellValue(alarmhisDataVo.getCustomerName());
                row.createCell(2).setCellValue(alarmhisDataVo.getControlName());
                row.createCell(3).setCellValue(alarmhisDataVo.getDataAddress());
                row.createCell(4).setCellValue(alarmhisDataVo.getAlarmcontent());
                row.createCell(5).setCellValue(alarmhisDataVo.getDatavalue());
                row.createCell(6).setCellValue(alarmhisDataVo.getCreatetime());
            }
        }

        //第六步,输出Excel文件
        OutputStream output = response.getOutputStream();
        response.reset();
        //设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        // 获取当前系统时间
        String fileName = df.format(new Date());
        //设置导出文件表头（即文件名）
        response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls");
        //设置返回内容类型
        response.setContentType("application/msexcel");
        response.setHeader("Access-Control-Allow-Origin", "*");
        wb.write(output);
        output.close();
    }


    private List<AlarmhisdataEntity> addMessage(List<AlarmhisdataEntity> list) {
        List<AlarmhisdataEntity> collect = list.stream().map(entity -> {
            Long customerid = entity.getCustomerid();
            CustomerEntity customerEntity = customerService.getById(customerid);
            entity.setCustomerName(customerEntity.getCustomername());

            Long machineid = entity.getMachineid();
            MachineEntity machineEntity = machineService.getById(machineid);
            entity.setMachineName(machineEntity.getMachinename());
            Long datatemplateid = entity.getDatatemplateid();
            DatatemplateEntity datatemplateEntity = datatemplateService.getById(datatemplateid);
            entity.setControlName(datatemplateEntity.getControlname());
            return entity;
        }).collect(Collectors.toList());
        return collect;
    }

}